package com.summer.shopping.controller;

import cn.hutool.core.bean.BeanUtil;
import com.summer.shopping.domain.table.Product;
import com.summer.shopping.domain.table.dto.PageDTO;
import com.summer.shopping.domain.table.dto.ProductQueryParam;
import com.summer.shopping.domain.table.vo.ProductVo;
import com.summer.shopping.service.ProductService;
import com.summer.shopping.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@CrossOrigin("*")
@RequestMapping("product")
public class ProductController {
    @Autowired
    private ProductService productService;
    //商品分页查询
    @GetMapping("/pages")
    public Result getProductPages(PageDTO pageDTO,ProductQueryParam param){
        return Result.ok(productService.pageQuery(pageDTO,param));
    }
    //商品细节查询
    @GetMapping("/item/{id}")
    public Result getProductInfo(@PathVariable Integer id){

        Product product = productService.getById(id);
        ProductVo productVo = BeanUtil.copyProperties(product, ProductVo.class);
        return Result.ok(productVo);
    }

    //商品的增，删，改
    // 创建商品
    @PostMapping
    public Result createProduct(@RequestBody Product product) {
        productService.save(product);
        return Result.ok("success");
    }

    // 删除商品
    @DeleteMapping("/{id}")
    public Result deleteProduct(@PathVariable Long id) {
        productService.removeById(id);
        return Result.ok("success");
    }

    // 更新商品
    @PutMapping
    public Result updateProduct(@RequestBody Product product) {
        Long id = product.getId();
        if (id==null)return Result.error("商品id不能为空");
        productService.updateById(product);
        return Result.ok("success");
    }
    // 根据ID查询商品（更新表单时，需要先查一下）
    @GetMapping("/{id}")
    public Result<Product> getProductById(@PathVariable Long id) {
        Product byId = productService.getById(id);
        return Result.ok(byId);
    }

}
